import axios from 'axios'
import errorCode from './errorCode'
import { tansParams, popMessage } from '../../utils/normalUtils'
import {getCookieToken, getToken} from '../../manager/permission'
import {appState, initReloadSystem, isEmbedMode} from '../../manager/appManager'
import { changeToLogin } from '../../../router'
const errors:any = errorCode
// 是否显示重新登录
let isReLoginShow: boolean
// 默认请求格式
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 创建axios实例
const service = axios.create({
  // 超时
  timeout: 300000
})

// request拦截器
service.interceptors.request.use(
  (config: any) => {
      if (!config.headers) { config.headers = {} }
      if (config.headers.isToken !== 'false') {
          const token = getCookieToken()
          if(!token){
              initReloadSystem()
              return
          }
          config.headers.authorization = token
      } else if (Object.prototype.hasOwnProperty.call(config.headers, 'authorization')) {
          delete config.headers.authorization
      }
    // get请求映射params参数
    if (config.method === 'get' && config.params) {
      let url = config.url + '?' + tansParams(config.params)
      url = url.slice(0, -1)
      config.params = {}
      config.url = url
    }
    if (config.method === 'post' && config.data instanceof FormData) {
        config.headers['Content-Type'] = 'multipart/form-data'
    }
    return config
  },
  (error) => {
    console.log(error)
    Promise.reject(error)
  }
)


// 响应拦截器
service.interceptors.response.use(
  (res) => {
    // 二进制数据则直接返回
    if (res.request.responseType === 'blob' ||
            res.request.responseType === 'arraybuffer'
        ) {
          const indexs = res.headers['content-disposition'].indexOf('=')
          const resolves = res.headers['content-disposition'].substring(indexs + 1, res.headers['content-disposition'].length)

        return {
          data: res.data,
          fileName: resolves
        }
    } else if (res.config && (res.config as any).origin === true) {
      return res.data
  }
    // 未设置状态码则默认成功状态
    const code = res.data.code || 'SUCCESS'

    // 获取错误信息
    const msg = errors[code] || res.data.msg || res.data.message || errorCode.default
    if (code === 401) {
      if (!isReLoginShow) {
          isReLoginShow = true
        // 登录状态已过期，您可以继续留在该页面，或者重新登录
         popMessage('登录状态已过期，请重新登录！', 'error')
      }
      return Promise.reject(res)
    } else if (code === 500) {
        popServiceMessage(res, msg, 'error')
      return Promise.reject(res)
    } else if (code === 'TOKEN_EXPIRE') {
      error401Handler(res, msg)
      return Promise.reject(res)
    } else if (code !== 'SUCCESS') {
        popServiceMessage(res, msg, 'error')
      return Promise.reject(res)
    } else {
      return Promise.resolve(res.data.data)
    }
  },
  (error) => {
    console.log('err', error)
    let { message } = error
    if (error.response.data.code === 'TOKEN_EXPIRE') {
       error401Handler(error)
    } else if (message === 'Network Error') {
      message = '后端接口连接异常'
    } else if (message.includes('timeout')) {
      message = '系统接口请求超时'
    } else if (message.includes('Request failed with status code')) {
      message = '系统接口' + message.substr(message.length - 3) + '异常'
    }
      popServiceMessage(error, message, 'error')
    return Promise.reject(error)
  }
)

/**
 * 401处理
 * @param res
 * @param msg
 */
function error401Handler(res:any, msg = '') {
    isReLoginShow = true
    // 纯本地测试不处理
    if (appState.debugMode) return
    // 登录状态已过期，您可以继续留在该页面，或者重新登录
    popMessage('登录状态已过期，请重新登录！', 'error')
    // 切换登录页面
    changeToLogin()
}

/**
 * 默认提示错误信息
 * @param res
 * @param message
 * @param type
 */
 function popServiceMessage(res:any, message:string, type = 'error') {
     if (res.config.popError === false) return
     popMessage(message, type, 5000)
 }


/**
 * 获得服务返回的错误信息
 * @param res
 * @param defaultMsg
 */
export function getServiceErrorMsg(res:any, defaultMsg = '') {
    const code = 'default'
    let result = res
    if (res.data) result = res.data
    return result.msg || result.message || defaultMsg || errors[code]
}

export default service

// 创建axios实例
export const localService = axios.create({ timeout: 20000 })
// 响应拦截器
localService.interceptors.response.use(
    (res) => {
       return Promise.resolve(res.data)
    },
    (error) => {
        console.log('err' + error)
        popMessage('数据请求失败', 'error', 5000)
        return Promise.reject(error)
    }
)

